package com.nl.lib_core.tool.extends

import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*

/** 作者: wangfei 创建时间: 2021/12/9 包名: com.nl.lib_core.util.extends 类名: FlowWxtends */

/** 倒计时 */
fun countDownCoroutines(
    total: Int,
    onTick: (Int) -> Unit,
    onFinish: () -> Unit,
    scope: CoroutineScope = GlobalScope
): Job {
  return flow {
        (total downTo 1).forEach {
          emit(it)
          delay(1000)
        }
      }
      .flowOn(Dispatchers.IO)
      .onCompletion { onFinish.invoke() }
      .onEach { onTick.invoke(it) }
      .flowOn(Dispatchers.Main)
      .launchIn(scope)
}

fun countUtilCoroutines(
    total: Int,
    onTick: (Int) -> Unit,
    onFinish: () -> Unit,
    scope: CoroutineScope = GlobalScope
): Job {
  return flow {
        (0 until total).forEach {
          delay(2000)
          emit(it)
        }
      }
      .flowOn(Dispatchers.IO)
      .onCompletion { onFinish.invoke() }
      .onEach { onTick.invoke(it) }
      .flowOn(Dispatchers.Main)
      .launchIn(scope)
}
